package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.Result;
import com.wing.purchase.model.entity.SupplierDueEnclosure;
import com.wing.purchase.model.response.SupplierDueSubjectCategoryVO;
import com.wing.purchase.model.response.SupplierDueSubjectVO;
import com.wing.purchase.service.SupplierDueEnclosureService;
import com.wing.purchase.service.SupplierDueSubjectCategoryService;
import com.wing.purchase.service.SupplierDueSubjectService;
import com.wing.sell.model.entity.AgentDue;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.SupplierDue;
import com.wing.purchase.model.request.SupplierDueForm;
import com.wing.purchase.service.SupplierDueService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-供应商尽调记录表管理", tags = "#/purchase/supplierDue")
@RestController("supplierDueController")
@RequestMapping("purchase/admin/supplierDue")
@RequiredArgsConstructor
@Slf4j
public class SupplierDueController {

    private final SupplierDueService supplierDueService;
    private final SupplierDueSubjectCategoryService supplierDueSubjectCategoryService;
    private final SupplierDueSubjectService supplierDueSubjectService;


    @ApiOperation(value = "查询所有供应商尽调记录表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SupplierDue> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long purSupId //供应商ID
    ){

        Page<SupplierDue> pg = new Page<>(page, limit);
        QueryWrapper<SupplierDue> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        //搜索
        if (purSupId !=null){
            queryWrapper.eq("pur_sup_id", purSupId);
        }
        IPage<SupplierDue> list = supplierDueService.getBaseMapper().selectPage(pg, queryWrapper);

        //关联相关业务属性
        list.getRecords().parallelStream().forEach(k -> {
            SupplierDueSubjectCategoryVO supplierDueSubjectCategoryVO = supplierDueSubjectCategoryService.get4appById(k.getCategoryId());
            if(null != supplierDueSubjectCategoryVO){
                k.setCategoryName(supplierDueSubjectCategoryVO.getName());
            }
            SupplierDueSubjectVO supplierDueSubjectVO = supplierDueSubjectService.get4appById(k.getSubjectId());
            if (null !=supplierDueSubjectVO){
                k.setSubjectName(supplierDueSubjectVO.getName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加供应商尽调记录表", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@RequestBody SupplierDueForm supplierDueForm) {
        try{
            supplierDueService.add(supplierDueForm);
            return JsonResult.success("添加成功！");
        }catch(Exception e){
            log.error("添加失败！",e);
            return JsonResult.fail("添加失败！"+e.getMessage());
        }
    }

    @ApiOperation(value = "批量添加供应商尽调记录表", notes = "添加")
    @PostMapping("/addList")
    public JsonResult addList(@RequestBody List<SupplierDueForm> list) {
        try{
            //新添加的有重复的分类和科目 不让添加
            Set<HashMap> s = new HashSet<>();
            for(SupplierDueForm supplierDueForm:list){
                s.add(new HashMap(){{put(supplierDueForm.getCategoryId(),supplierDueForm.getSubjectId());}});
            }
            if (s.size()!=list.size()){
                //return JsonResult.fail("添加的尽调分类和尽调科目存在重复,请删除重复项后再保存");
                return JsonResult.error(500,"添加的尽调分类和尽调科目存在重复,请删除重复项后再保存");
            }

            //查询该供应商已经添加过的尽调信息  分类和科目
            List<SupplierDue> supplierDues =supplierDueService.list(new QueryWrapper<SupplierDue>().eq("pur_sup_id",list.get(0).getPurSupId()));
            if (supplierDues!=null){
                for (SupplierDue supplierDue:supplierDues){
                    for(SupplierDueForm supplierDueForm:list){
                        if (supplierDue.getCategoryId()==supplierDueForm.getCategoryId()&&supplierDue.getSubjectId()==supplierDueForm.getSubjectId()){
                            //有重复的不让添加
                            return JsonResult.fail("分类:    "+supplierDueSubjectCategoryService.get4appById(supplierDue.getCategoryId()).getName()+"   科目:    "+supplierDueSubjectService.get4appById(supplierDue.getSubjectId()).getName()+"   已添加,请勿重复添加");
                        }
                    }
                }
            }

            for(SupplierDueForm supplierDueForm:list){
                supplierDueService.add(supplierDueForm);
            }
            return JsonResult.success("添加成功！");
        }catch(Exception e){
            log.error("添加失败！",e);
            return JsonResult.fail("添加失败！"+e.getMessage());
        }
    }


    @ApiOperation(value = "修改供应商尽调记录表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody SupplierDueForm supplierDueForm) {
        try{
            supplierDueService.update(supplierDueForm);
            return JsonResult.success("修改成功！");
        }catch(Exception e){
            log.error("修改失败！",e);
            return JsonResult.fail("修改失败！"+e.getMessage());
        }
    }



    @ApiOperation(value = "删除供应商尽调记录表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplierDueId", value = "供应商尽调记录表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long supplierDueId) {
        if (supplierDueService.removeById(supplierDueId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "审核", notes = "审核")
    @PutMapping("/check")
    public JsonResult check(@RequestBody SupplierDueForm supplierDueForm) {
        SupplierDue supplierDue = this.supplierDueService.getById(supplierDueForm.getId());
        if(supplierDue == null){
            return JsonResult.fail("审核失败！");
        }
        supplierDue.setStatus(supplierDueForm.getStatus());
        supplierDue.setAuditor(JwtUtils.getLoginUsername());
        supplierDue.setAuditTime(LocalDateTime.now());
        if (this.supplierDueService.updateById(supplierDue)) {
            return JsonResult.success("审核成功！");
        }
        return JsonResult.fail("审核失败！");
    }

}
